﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Text;
using System.Net.Mail;
using Helper;
using System.Data.Linq;
using System.Configuration;

namespace MVC2_Test.Models
{
    public class GuestResponse : IDataErrorInfo
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public bool? WillAttend { get; set; }

        public string Error { get { return null; } }

        public string this[string propName]
        {
            get
            {
                if ((propName == "Name") && string.IsNullOrEmpty(Name))
                    return "이름을 입력해 주세요.";
                if ((propName == "Email") && string.IsNullOrEmpty(Email) && !Regex.IsMatch(Email, ".+\\@.+\\..+"))
                    return "이메일 주소를 올바르게 입력해 주세요.";
                if ((propName == "Phone") && string.IsNullOrEmpty(Phone))
                    return "전화번호를 입력해 주세요.";
                if ((propName == "WillAttend") && !WillAttend.HasValue)
                    return "attend를 선택해 주세요.";

                return null;
            }
        }

        public void Submit()
        {
            EnsuerCurrentlyValid();
            
            // 이메일 발송
            var message = new StringBuilder();
            message.AppendFormat("Date: {0:yyyy-MM-dd hh:mm}\n", DateTime.Now);
            message.AppendFormat("RSVP from: {0}\n", Name);
            message.AppendFormat("Email: {0}\n", Email);
            message.AppendFormat("Phone: {0}\n", Phone);
            message.AppendFormat("Can com: {0}\n", WillAttend.Value ? "Yes" : "No");



            EmailHelper mail = new EmailHelper();

            mail.To = "ksyang77@naver.com";
            mail.Subject = Name + (WillAttend.Value ? " will attend" : " won't attend");
            mail.Body = message.ToString();

            mail.Send();

            if (mail.ErrorMsg != "OK")
            {
                throw new InvalidOperationException(mail.ErrorMsg);
            }
            
        }

        private void EnsuerCurrentlyValid()
        {
            // 모든 속성들에 대해 IDataErrorInfo.this[]가 null을 반환하면 OK
            var propsToValidate = new[] { "Name", "Email", "Phone", "WillAttend" };
            bool isValid = propsToValidate.All(x => this[x] == null);
            if (!isValid)
                throw new InvalidOperationException("유효하지 않은 GuestResponse 입니다.");

        }



    }
}